﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace AutoUpgrade
{
    /// <summary>
    /// xml版本配置解析类
    /// </summary>
    internal class XmlVersionConfig
    {
        public XmlVersionConfig(string Xml)
        {
            Xml = Xml.Trim();
            this.Xml = Xml;

            ParseXmlVersionFile(this.Xml);
        }

        public string Xml { get; set; }

        public Version MainVersion { get; set; } = new Version("0.0.0.0");

        public DateTime DateTime { get; set; } = DateTime.MinValue;
        public string Description { get; set; } = string.Empty;
        public List<VersionInfo> FileList { get; set; } = null;

        /// <summary>
        /// 获取或设置指定索引处的元素。
        /// </summary>
        /// <param name="name">元素的 name 属性</param>
        /// <returns></returns>
        public VersionInfo this[string name]
        {
            get => this.FileList.FirstOrDefault(item => item.Name == name);
        }

        public bool ContainsKey(string name)
        {
            return this.FileList.Exists(item => item.Name == name);
        }

        /// <summary>
        /// 开始解析
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        private bool ParseXmlVersionFile(string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            this.MainVersion = new Version(doc.SelectSingleNode("package").SelectSingleNode("metadata").SelectSingleNode("version").InnerText);
            this.Description = doc.SelectSingleNode("package").SelectSingleNode("metadata").SelectSingleNode("description").InnerText;

            this.FileList = new List<VersionInfo>();
            foreach (XmlElement xmlElement in doc.SelectSingleNode("package").SelectSingleNode("files"))
            {
                VersionInfo Info = new VersionInfo();
                Info.Type = xmlElement.Name;
                Info.Name = xmlElement.Attributes["name"].Value;
                Info.Version = new Version(xmlElement.Attributes["version"].Value);
                Info.Size = int.Parse(xmlElement.Attributes["size"].Value);
                if (xmlElement.Attributes["uri"] != null)
                    Info.Uri = xmlElement.Attributes["uri"].Value;
                if (xmlElement.Attributes["md5"] != null)
                    Info.Md5 = xmlElement.Attributes["md5"].Value;
                this.FileList.Add(Info);
            }
            return true;
        }
    }

}
